

import nw from "nw-lafjs";
import {ok} from "@/utils/responseUtil";

async function getLeaderAddressVo(ctx: FunctionContext) {
  let id = ctx.user.admin
  //查询团长数据
  let queryData = {deleted:0,userId:id,isDefault:1}
  let userDelivery = await nw.db.findByWhereJson({
    dbName:"userDelivery",
    whereJson:queryData
  })
  if (nw.util.isNull(userDelivery)){
    return Promise.resolve(null)
  }
  //根据id查询团长数据
  let leader = await nw.db.findById({
    dbName:"leader",
    id:userDelivery.leaderId
  })
  if (nw.util.isNull(leader)){
    return Promise.resolve(null)
  }

  let leaderAddressVo = {
    userId:leader.userId,
    leaderId:leader._id,
    leaderName:leader.name,
    leaderPhone:leader.phone,
    wareId:leader.wareId,
    takeName:leader.takeName,
    storePath:leader.storePath
  }
  return Promise.resolve(leaderAddressVo)
}

async function getCategoryList() {
  return nw.db.findListByWhereJson({
    dbName:"category",
    whereJson:{deleted:0}
  })
}

async function getNewPersonSkuInfoList() {
  //1.查询新人专享sku数据
  return nw.db.findListByWhereJson({
    dbName:"skuInfo",
    whereJson:{deleted:0,isNewPerson:1,publishStatus:1,checkStatus:1}
  })
}

async function getHotSkuList() {
  //1.查询点击量前十的数量
  let hotSku = await nw.db.select({
    dbName:"skuInfo",
    getCount:false,
    pageIndex:1,
    pageSize:10,
    whereJson:{deleted:0,publishStatus:1,checkStatus:1},
    sortArr: [{ "name": "clickCount","type": "desc" }]
  })
  if (nw.util.isNull(hotSku)){
    return Promise.resolve([])
  }
  return Promise.resolve(hotSku.rows)

}

export default async function (ctx: FunctionContext) {
  let result = {
    "categoryList": [],
    "newPersonSkuInfoList": [],
    "leaderAddressVo": [],
    "hotSkuList": []
  }
  //1.查询团长收获地址
  let leaderAddressVo = await getLeaderAddressVo(ctx)
  result.leaderAddressVo = leaderAddressVo
  //2.查询商品分类
  let categoryList = await getCategoryList()
  result.categoryList = categoryList
  //3.获取新人专享商品sku
  let newPersonSkuInfoList = await getNewPersonSkuInfoList()
  result.newPersonSkuInfoList = newPersonSkuInfoList
  //4.获取热门数据skuInfo
  let hotSkuList = await getHotSkuList()
  result.hotSkuList = hotSkuList
  return ok(result)
}
